package com.clz.mycustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.clz.mycustomview.R;

/**
 * 圆形头像 通过canvas的clip放放风 裁减画布
 */
public class CustomCircleView extends View {
    private Bitmap bitmap;
    private Paint mPaint;
    private Path mPath;

    public CustomCircleView(Context context) {
        super(context);
        init();
    }

    public CustomCircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init(){
        // 禁用硬件加速功能，否则canvas的clip无效
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator);
        mPaint = new Paint();
        mPath = new Path();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        mPath.addCircle(width/2,height/2, width/2, Path.Direction.CCW);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.clipPath(mPath);
        canvas.drawBitmap(bitmap,0,0,mPaint);
        canvas.restore();
    }
}
